package com.witdata.config.aspect.service;

import com.witdata.common.domain.req.LoginRequest;
import com.witdata.mysql.base.service.UserLearningSessionService;
import com.witdata.mysql.domain.entity.TUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import static com.witdata.common.constant.RedisConstant.REDISKEYLOGIN;


@Component
public class LoginAsyncService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private UserLearningSessionService userLearningSessionService;

    private static final Logger logger = LoggerFactory.getLogger(LoginAsyncService.class);

    @Async
    public void recordLoginInfoAsync(LoginRequest loginRequest) {
//        try {
//            Date date = new Date();
//            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//            String formattedDate = sdf.format(date);
//
//            String dailyKey = loginRequest.getUsername() + date.getDay();
//            redisTemplate.opsForValue().set(dailyKey, formattedDate, 1, TimeUnit.DAYS);
//            redisTemplate.opsForValue().set(REDISKEYLOGIN + "userName", loginRequest.getUsername(), 1, TimeUnit.DAYS);
//            TUser tuser = userLearningSessionService.selectByUserName(loginRequest.getUsername());
//            if (tuser == null) {
//                logger.error("用户不存在: {}", loginRequest.getUsername());
//                return;
//            }
//            long startTime = System.currentTimeMillis();
//            long lastTime = System.currentTimeMillis();
//            Long id = tuser.getId();
//
//            if (Objects.isNull(userLearningSessionService.findByUsername(loginRequest.getUsername()))) {
//                userLearningSessionService.saveUserName(id, loginRequest.getUsername(), startTime, lastTime);
//            } else {
//                userLearningSessionService.saveTimeByUserName(loginRequest.getUsername(), startTime, lastTime);
//            }
//        } catch (Exception e) {
//            logger.error("登录记录失败: {}", e.getMessage());
//        }
    }
}